<script lang="ts" setup>
import type {
  GridInstance as VxeGridInstance,
  VxeGridListeners,
  VxeGridProps,
} from '#/adapter/vxe-table';
import type { ArticleApi } from '#/api/core/article';

import { computed, onMounted, ref } from 'vue';
import { useRouter } from 'vue-router';

import { Button, Form, message, Modal, Select } from 'ant-design-vue';

import { useVbenVxeGrid } from '#/adapter/vxe-table';
import { getArticleCategoriesApi, getArticleListApi } from '#/api/core/article';
import { requestClient } from '#/api/request';

// 表格引用
const gridRef = ref<VxeGridInstance>();

// 存储表格数据
const tableData = ref<ArticleApi.ArticleInfo[]>([]);

// 分页相关
const currentPage = ref(1);
const totalPage = ref(0);

// 文章分类列表
const categories = ref<ArticleApi.ArticleCategory[]>([]);

// 搜索表单数据
const searchForm = ref({
  article_type: -1,
});

const router = useRouter();

// 获取文章分类
async function loadCategories() {
  try {
    const response = await getArticleCategoriesApi();
    categories.value = response;
  } catch {
    message.error('获取文章分类失败');
  }
}

// 表格配置
const gridOptions = computed<VxeGridProps<ArticleApi.ArticleInfo>>(() => ({
  columns: [
    { field: 'article_title', title: '标题', minWidth: 100 },
    { field: 'article_type', title: '文章类型', width: 120 },
    {
      field: 'publish_time',
      title: '发布时间',
      width: 180,
      formatter: ({ cellValue }) => {
        if (!cellValue) return '';
        return new Date(cellValue).toLocaleString('zh-CN', {
          year: 'numeric',
          month: '2-digit',
          day: '2-digit',
          hour: '2-digit',
          minute: '2-digit',
          second: '2-digit',
          hour12: false,
        });
      },
    },
    {
      title: '操作',
      width: 160,
      slots: {
        default: 'operate',
      },
    },
  ],
  data: tableData.value,
  pagerConfig: {
    enabled: true,
    pageSize: 10,
    total: totalPage.value * 10,
    currentPage: currentPage.value,
    layouts: ['PrevPage', 'JumpNumber', 'NextPage', 'FullJump', 'Total'],
    perfect: true,
  },
}));

// 表格事件
const gridEvents: VxeGridListeners<ArticleApi.ArticleInfo> = {
  pageChange: ({ currentPage: newPage }) => {
    currentPage.value = newPage;
    loadData();
  },
};

const [Grid, gridApi] = useVbenVxeGrid({
  gridEvents,
  gridOptions: gridOptions.value,
});

// 加载数据
async function loadData() {
  try {
    gridApi.setLoading(true);
    const params: ArticleApi.ArticleListParams = {
      current_page: currentPage.value,
      article_type: searchForm.value.article_type,
    };

    const response = await getArticleListApi(params);
    if (Array.isArray(response)) {
      tableData.value = response;
      // 假设返回数据中包含总页数信息
      const total_page = response[0]?.total_page || 0;
      totalPage.value = total_page;

      gridApi.setGridOptions({
        data: tableData.value,
        pagerConfig: {
          ...gridOptions.value.pagerConfig,
          total: total_page * 10,
          currentPage: currentPage.value,
        },
      });
    }
  } catch {
    message.error('获取文章列表失败');
    tableData.value = [];
  } finally {
    gridApi.setLoading(false);
  }
}

// 搜索
function handleSearch() {
  currentPage.value = 1;
  loadData();
}

// 重置
function handleReset() {
  currentPage.value = 1;
  searchForm.value.article_type = -1;
  loadData();
}

// 新增文章
function handleAdd() {
  router.push('/article/add');
}

// 编辑文章
function handleEdit(row: ArticleApi.ArticleInfo) {
  // 将文章数据存储到 localStorage
  localStorage.setItem('editArticleData', JSON.stringify(row));

  router.push({
    path: '/article/add',
    query: { type: 'edit' },
  });
}

// 删除文章
function handleDelete(row: ArticleApi.ArticleInfo) {
  Modal.confirm({
    title: '确认删除',
    content: '确定要删除这篇文章吗？',
    async onOk() {
      try {
        await requestClient.post('/v1/delete/article/', { id: row.id });
        message.success('删除成功');
        loadData(); // 重新加载列表
      } catch {
        message.error('删除失败');
      }
    },
  });
}

onMounted(() => {
  loadCategories();
  loadData();
});
</script>

<template>
  <div class="p-4">
    <!-- 搜索表单 -->
    <Form class="mb-4" layout="inline">
      <Form.Item label="文章分类">
        <Select
          v-model:value="searchForm.article_type"
          placeholder="请选择文章分类"
          style="width: 200px"
        >
          <Select.Option :value="-1">全部</Select.Option>
          <Select.Option
            v-for="category in categories"
            :key="category.id"
            :value="category.id"
          >
            {{ category.name }}
          </Select.Option>
        </Select>
      </Form.Item>
      <Form.Item>
        <Button class="mr-2" type="primary" @click="handleSearch">搜索</Button>
        <Button class="mr-2" @click="handleReset">重置</Button>
        <Button type="primary" @click="handleAdd">新增文章</Button>
      </Form.Item>
    </Form>

    <div class="vp-raw w-full">
      <Grid ref="gridRef">
        <template #operate="{ row }">
          <Button type="link" @click="handleEdit(row)"> 编辑 </Button>
          <Button danger type="link" @click="handleDelete(row)"> 删除 </Button>
        </template>
      </Grid>
    </div>
  </div>
</template>
